package com.jhoncy.rapid.auth.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * 鉴权：自定义认证
 * @author zhuangqi
 * @date 2017/7/21.
 */
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private AuthUserDetailsService authUserDetailsService;

    @Bean
    public Md5PasswordEncoder md5PasswordEncoder() {
        return new Md5PasswordEncoder();
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        String username = token.getName();
        //从数据库找到的用户
        AuthUser authUser = null;
        if (username != null) {
            authUser = (AuthUser) authUserDetailsService.loadUserByUsername(username);
        }
        if (authUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        } else if (!authUser.isEnabled()) {
            throw new DisabledException("用户已被禁用");
        }
        //数据库用户的密码
        String encPass = authUser.getPassword();
        //与authentication里面的credentials相比较
        Md5PasswordEncoder md5PasswordEncoder = this.md5PasswordEncoder();
        if (!md5PasswordEncoder.isPasswordValid(encPass, token.getCredentials().toString(), null)) {
            throw new BadCredentialsException("无效的用户名或密码");
        }
        //将用户信息存入Authentication的Token中，将由spring-Security自动鉴权。
        return new UsernamePasswordAuthenticationToken(authUser, encPass, authUser.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        //token中的name是否与security保存的用户信息中的name是否相同，如果相同鉴权成功
        return UsernamePasswordAuthenticationToken.class.getName().equals(authentication.getName());
    }
}
